package catalina.container;

import catalina.connection.Request;
import catalina.connection.Response;

import java.io.File;
import java.net.URL;
import java.util.Properties;

public class StandardHost extends ContainerBase {
    @Override
    public void initInternal() {
        Properties properties = getProperties();
        String appBase = (String) properties.get("appBase");
        File file = new File(appBase);
        if (!file.isAbsolute()) {
            URL resource = Thread.currentThread().getContextClassLoader().getResource(appBase);
            if (resource == null) {
                return;
            }
            appBase = resource.getFile();
            file = new File(appBase);
        }
        parseContext(file);
    }

    @Override
    public void startInternal() {

    }

    @Override
    public void stopInternal() {

    }

    @Override
    public void destroyInternal() {

    }

    @Override
    public void service(Request request, Response response) {
        Container context = findChild(request.getMapper().getContextName());
        if (context != null) {
            context.service(request, response);
        }
    }

    private void parseContext(File file) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File subFile : files) {
                String contextName = subFile.getName();
                Container contextContainer = new StandardContext();
                contextContainer.setName(contextName);
                Properties properties = new Properties();
                properties.put("contextFile", subFile);
                contextContainer.setProperties(properties);
                contextContainer.setParent(this);
                addChild(contextContainer);
            }
        }
    }
}
